﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using Bonobo.Irc.Client.UI.Data;
using System.Threading;

namespace Bonobo.Irc.Client.UI
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly SynchronizationContext _syncContext;

        public MainWindow()
        {
            _syncContext = SynchronizationContext.Current;
            _syncContext.Post(() => ConversationProvider.Conversations.Add(new UIServerConversation(new IrcSession()) { Header = "Connection number " + ConversationProvider.Conversations.Count.ToString() }));
            InitializeComponent();
        }


        private IrcConversationProvider ConversationProvider
        {
            get { return (IrcConversationProvider)Resources["ConversationProvider"]; }
        }

        private void CloseExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            foreach (var item in ConversationProvider.Conversations)
            {
                if (item is UIServerConversation)
                {
                    item.Session.Close();
                }
            }
            Application.Current.Shutdown();
        }

        protected override void OnClosed(EventArgs e)
        {
            foreach (var item in ConversationProvider.Conversations)
            {
                if (item is UIServerConversation)
                {
                    item.Session.Close();
                }
            }

            base.OnClosed(e);
        }

        private void DisconnectExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            if (tabConversations.SelectedItem != null)
            {
                var session = ((UIServerConversation)tabConversations.SelectedItem).Session;
                if (session.State != IrcSessionState.Closed && session.State != IrcSessionState.Closing)
                {
                    session.Close();
                }
            }
        }

        private void ConnectExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            _syncContext.Send(() => ConversationProvider.Conversations.Add(new UIServerConversation(new IrcSession()) { Header = "Connection number " + ConversationProvider.Conversations.Count.ToString() }));
            tabConversations.SelectedItem = tabConversations.Items[tabConversations.Items.Count - 1];
        }

    }

}
